package com.neusoft.service.impl;

import java.security.MessageDigest;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.mapper.AuthMapper;
import com.neusoft.po.Token;
import com.neusoft.service.AuthService;

@Service
public class AuthServiceImpl implements AuthService{

	@Autowired
	private AuthMapper authMapper;
	
	@Override
	public String getToken(String userId) {
		// 补齐至32位后使用md5加密
		String randomString = generateRandomString(21);
		String input = userId + randomString;
		String token = new String();
		try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] mdBytes = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : mdBytes) {
                sb.append(String.format("%02x", b));
            }
            
            token = sb.toString();
            
        } catch (Exception e) {
            token = null;
            e.printStackTrace();
        }
		
		Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);

        String timeGenerated = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
        Token T = new Token();
        T.setTokenId(0);
        T.setToken(token);
        T.setUserId(userId);
        T.setTimeGenerated(timeGenerated);
        T.setValid(1);
		authMapper.saveToken(T);
        return token;
	}

	@Override
	public Token checkValid(String token) {
		List<Token> resultList = authMapper.getToken(token);
		for (Token resultT : resultList) {
			return resultT;
		}
		
		return null;
	}

	@Override
	public String generateRandomString(int length) {
		String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        
        return sb.toString();
	}

}
